package com.alipay.rebate.shop.utils;

import com.alipay.rebate.shop.exceptoin.TokenExpireException;
import com.alipay.rebate.shop.exceptoin.TokenIdNotRightException;
import com.alipay.rebate.shop.exceptoin.TokenNotValidException;
import com.alipay.rebate.shop.exceptoin.TokenPhoneNotRightException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class TokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    private static final String[] codeBase= {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    private static Random rand= new Random();

    /** XXTEA加密解密的密钥 */
    private static String secKey = "captcha";

    /** token超时门限(天) */
    private static long expire = 30;


    /** 验证码字符数 */
    private static int charCount = 4;

    public static final  String  genToken(Long userId) {
        StringBuffer sb= new StringBuffer();
        for(int i=0; i<charCount; i++){
            int randInt= Math.abs(rand.nextInt());
            sb.append(codeBase[randInt % codeBase.length]);
        }
        long timestamp= System.currentTimeMillis();
        String token= null;
        token= String.format("%s_%d_%d", sb.toString(), timestamp,userId);
        System.out.println("未加密的token:"+token);
        token= XXTEAUtil.encrypt(token, secKey);
        return token;
    }

    public static final boolean verificationToken(String token,long id){
        logger.debug("token is : {}",token);
        String plainText = null;
        try {
            plainText= XXTEAUtil.decrypt(token, secKey);
        }catch (Exception e){
            logger.debug("error when decode token");
        }
        logger.debug("plainText is : {}",plainText);
        if (StringUtils.isBlank(plainText) || plainText == null){
            throw new TokenNotValidException();
        }
        String[] plainTextArr= plainText.split("_");
        if (plainTextArr.length!=3){
            throw new TokenNotValidException();
        }

        long timestamp= Long.parseLong(plainTextArr[1]);
        long decodeId =  Long.parseLong(plainTextArr[2]);
        logger.debug("decodeId is : {}",decodeId);
        // token 过期
        if ((System.currentTimeMillis() - timestamp)> TimeUnit.MILLISECONDS.convert(expire+5, TimeUnit.DAYS)){
            throw new TokenExpireException();
        }
        // 用户id不匹配
        if(decodeId != id){
            throw new TokenIdNotRightException();
        }
        return true;
    }

}
